package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Psycho
 * @create 2022-04-26-21:36
 */
@Service
@Slf4j
@Transactional
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Autowired
    private WmNewsService wmNewsService;

    @Autowired
    private GreenTextScan greenTextScan;

    @Autowired
    private GreenImageScan greenImageScan;

    /**
     * 自媒体文章审核
     *
     * @param id 自媒体文章id
     */
    @Override
    @Async  //标明当前方法是一个异步方法
    public void autoScanWmNews(Integer id) {

        boolean flag = true;

        //1.查询自媒体文章
        if(id == null){
            return;
        }
        WmNews wmNews = wmNewsService.getById(id);
        if(wmNews == null){
            throw new RuntimeException("WmNewsAutoScanServiceImpl-文章不存在");
        }
        //状态为1：也就是提交(待审核)才进行审核
        if(wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())){
            //获取参数:文章内容跟图片信息
            String newsContent = wmNews.getContent();
            if(StringUtils.isBlank(newsContent)){
                return;
            }
            Map<String,Object> ValueMap = handleTextAndImages(newsContent);

            //自管理的敏感词过滤
            boolean isSensitive = handleSensitiveScan(ValueMap.get("text").toString(), wmNews);
            if(!isSensitive) return;


            //2.审核文本内容  阿里云接口
            boolean handleTextScan = handleTextScan(ValueMap,wmNews);
            if(!handleTextScan)return;

            //3.审核图片  阿里云接口
            boolean handleImageScan = handleImageScan(ValueMap,wmNews);
            if(!handleImageScan)return;

            //4.审核成功，保存app端的相关的文章数据
            ResponseResult responseResult = saveAppArticle(wmNews);

            if(!responseResult.getCode().equals(200)){
                throw new RuntimeException("WmNewsAutoScanServiceImpl-文章审核，保存app端相关文章数据失败");
            }
            //回填article_id
            wmNews.setArticleId((Long) responseResult.getData());
            updateWmNews(wmNews,(short) 9,"审核成功");
        }
    }


    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;

    /**
     * 自管理的敏感词审核
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleSensitiveScan(String content, WmNews wmNews) {

        boolean flag = true;

        //获取所有的敏感词
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
        List<String> sensitiveList = wmSensitives.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());

        //初始化敏感词库
        SensitiveWordUtil.initMap(sensitiveList);

        //查看文章中是否包含敏感词
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        if(map.size() >0){
            updateWmNews(wmNews,(short) 2,"当前文章中存在违规内容"+map);
            flag = false;
        }

        return flag;
    }


    @Autowired
    private IArticleClient articleClient;

    @Autowired
    private WmChannelMapper wmChannelMapper;

    @Autowired
    private WmUserMapper wmUserMapper;

    /**
     * 保存app端相关的文章数据
     * @param wmNews
     */
    private ResponseResult saveAppArticle(WmNews wmNews) {

        ArticleDto dto = new ArticleDto();
        //属性的拷贝
        BeanUtils.copyProperties(wmNews,dto);
        //文章的布局
        dto.setLayout(wmNews.getType());
        //频道
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if(wmChannel != null){
            dto.setChannelName(wmChannel.getName());
        }

        //作者
        dto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if(wmUser != null){
            dto.setAuthorName(wmUser.getName());
        }

        //设置文章id
        if(wmNews.getArticleId() != null){
            dto.setId(wmNews.getArticleId());
        }
        dto.setCreatedTime(new Date());
        ResponseResult responseResult = articleClient.saveArticle(dto);
        return responseResult;
    }

    @Autowired
    private FileStorageService fileStorageService;




    @Autowired
    private Tess4jClient tess4jClient;

    /**
     * 阿里的图片扫描
     * @param valueMap
     * @param wmNews
     * @return
     */
    private boolean handleImageScan(Map<String, Object> valueMap, WmNews wmNews) {

        boolean flag = true;
        List<String> images = (List<String>) valueMap.get("images");
        if(images == null || images.size() == 0){
            return flag;
        }
        //下载图片 minIO
        //图片去重
        images = images.stream().distinct().collect(Collectors.toList());

        List<byte[]> imageList = new ArrayList<>();

        try {
            for (String image : images) {
                byte[] bytes = fileStorageService.downLoadFile(image);

                //图片识别文字审核---begin-----

                //从byte[]转换为butteredImage
                ByteArrayInputStream in = new ByteArrayInputStream(bytes);
                BufferedImage imageFile = ImageIO.read(in);
                //识别图片的文字
                String result = tess4jClient.doOCR(imageFile);

                //审核是否包含自管理的敏感词
                boolean isSensitive = handleSensitiveScan(result, wmNews);
                if(!isSensitive){
                    return isSensitive;
                }

                //图片识别文字审核---end-----

                imageList.add(bytes);

            }
        }catch (Exception e){
            e.printStackTrace();
        }

        //审核图片
        try {
            Map map = greenImageScan.imageScan(imageList);
            if(map != null){
                //审核失败
                if(map.get("suggestion").equals("block")){
                    flag = false;
                    updateWmNews(wmNews, (short) 2, "当前文章中存在违规内容");
                }

                //不确定信息  需要人工审核
                if(map.get("suggestion").equals("review")){
                    flag = false;
                    updateWmNews(wmNews, (short) 3, "当前文章中存在不确定内容");
                }
            }

        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;

    }

    /**
     * 阿里的文本扫描
     * @param valueMap
     * @param wmNews
     * @return
     */
    private boolean handleTextScan(Map<String, Object> valueMap, WmNews wmNews) {
        boolean flag = true;
        String text = valueMap.get("text").toString();
        Map map = null;
        try {
            text = text + "-" + wmNews.getTitle();
            if(text.length() == 1){
                return false;
            }
            map = greenTextScan.greeTextScan(text);
            if(map.get("suggestion").equals("block")){
                updateWmNews(wmNews,(short) 2,"存在敏感词");
                flag = false;
            }
            if(map.get("suggestion").equals("review")){
                updateWmNews(wmNews,(short) 3,"当前文章中存在不确定内容");
                flag = false;
            }
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }

    private void updateWmNews(WmNews wmNews, short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsService.updateById(wmNews);
    }

    private Map<String,Object> handleTextAndImages(String newsContent) {
        //转化为JSONArry
        List<Map> maps = JSON.parseArray(newsContent, Map.class);
        //StringBuild用来拼接文本内容
        StringBuilder text = new StringBuilder();
        //List<String>用来接收图片地址
        List<String> imagesList = new ArrayList<>(maps.size());
        for (Map map : maps) {
            if(map.get("type").equals("text")){
                String value = map.get("value").toString();
                text.append(value);
            }
            if(map.get("type").equals("image")){
                String imagePath = map.get("value").toString();
                imagesList.add(imagePath);
            }
        }
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("text",text);
        resultMap.put("images",imagesList);
        return resultMap;
    }
}
